package com.util;

import java.util.Iterator;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONObject;

public class JsonXMLConvert {
	private StringBuilder resultXML = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?><transaction><type_id>I</type_id>");

	/**
	 * 特殊字符转换 spacialChars为特殊字符， validChars为将要转换的字符。这两个数组是一一对应的
	 */
	private static String[] spacialChars = { "&", "<", ">", "\"", "'" };
	private static String[] validChars = { "&amp;", "&lt;", "&gt;", "&quot;", "&apos;" };

	public String toXml(String jsonString) {
		try {
			JSONObject jsonObject = new JSONObject(jsonString);
			toXml(jsonObject);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return resultXML.toString()+"</transaction>";
	}
	
	public String toJson(String xmlString) {
		
		XMLSerializer xmlSerializer = new XMLSerializer();
		JSON json = xmlSerializer.read(xmlString);
		return json.toString();
	}

	private void toXml(JSONObject json) throws Exception {

		Iterator<?> keyIter = json.keys();
		while (keyIter.hasNext()) {
			String key = (String) keyIter.next();
			Object jsonValue = json.get(key);
			if (jsonValue instanceof JSONArray) {
				JSONArray arrayValue = (JSONArray) jsonValue;
				for (int i = 0; i < arrayValue.length(); i++) {
					appendFlagBegin(key);
					Object arrItem = arrayValue.get(i);
					if (arrItem instanceof JSONObject) {
						toXml((JSONObject) arrItem);
					} else if (arrItem instanceof JSONArray) {
						String arrItemStr = "{" + key + ":" + ((JSONArray) arrItem).toString() + "}";
						toXml(new JSONObject(arrItemStr));
					} else {
						appendText(arrItem.toString());
					}
					appendFlagEnd(key);
				}
			} else {
				appendFlagBegin(key);
				if (jsonValue instanceof JSONObject) {
					toXml((JSONObject) jsonValue);
				} else {
					appendText(jsonValue.toString());
				}
				appendFlagEnd(key);
			}
		}
	}

	/**
	 * 转换特殊字符
	 * @param s
	 * @return
	 */
	private static String replaceSpecialChar(String s) {
		for (int i = 0; i < spacialChars.length; i++) {
			s = s.replaceAll(spacialChars[i], validChars[i]);
		}
		return s;
	}

	private void appendText(String s) {
		resultXML.append(replaceSpecialChar(s));
	}

	private void appendFlagBegin(String str) {
		resultXML.append("<" + str + ">");
	}

	private void appendFlagEnd(String str) {
		resultXML.append("</" + str + ">");
	}
}
